package com.ceba.test.modules.upgrade.service;

import abc.data.DataTable;
import abc.data.Sql;
import abc.data.SqlSessionManager;
import com.ceba.base.dbdata.MysqlUtils;
import com.ceba.cebautils.StringUtil;
import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.configs.NettyServerConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by liguangyao on 2019/7/22.
 */
public class UpgradeService {
    private static Logger logger = LoggerFactory.getLogger(UpgradeService.class);

    /**
     * 保证当前版本号 和 使用版本号 一致
     * @param
     * @param
     * @throws Exception
     */
    public static void checkAndUpdateConfig() throws Exception{
        String version = CebaConfig.VERSION;

        /*Sql sql = new Sql("SELECT `KEY` FROM config WHERE 1=1 LIMIT 0, 10");
        DataTable dt = SqlSessionManager.getDataTable(sql);
        if (dt == null || dt.getRowCount() == 0 || StringUtil.isEmptyString(dt.getRow(0).getString("KEY")).booleanValue()) {
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/deploy/eq_3.6.0.sql");
            CebaConfig.init();
        }
        NettyServerConfig.init();*/

        if(StringUtils.equals(version, "3.5.0")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.0-3.5.1.sql");
            version = "3.5.1";
        }
        if(StringUtils.equals(version, "3.5.1")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.1-3.5.2.sql");
            version = "3.5.2";
        }
        if(StringUtils.equals(version, "3.5.2")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.2-3.5.3.sql");
            version = "3.5.3";
        }
        if(StringUtils.equals(version, "3.5.3")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.3-3.5.4.sql");
            version = "3.5.4";
        }
        if(StringUtils.equals(version, "3.5.4")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.4-3.5.5.sql");
            version = "3.5.5";
        }
        if(StringUtils.equals(version, "3.5.5")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.5-3.5.6.sql");
            version = "3.5.6";
        }
        if(StringUtils.equals(version, "3.5.6")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.6-3.5.7.sql");
            version = "3.5.7";
        }
        if(StringUtils.equals(version, "3.5.7")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.5.7-3.6.0.sql");
            version = "3.6.0";
        }
        if(StringUtils.equals(version, "3.6.0")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.6.0-3.6.1.sql");
            version = "3.6.1";
        }
        if(StringUtils.equals(version, "3.6.1")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.6.1-3.6.2.sql");
            version = "3.6.2";
        }
        if(StringUtils.equals(version, "3.6.2")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.6.2-3.6.3.sql");
            version = "3.6.3";
        }
        if(StringUtils.equals(version, "3.6.3")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.6.3-3.6.4.sql");
            version = "3.6.4";
        }
        if(StringUtils.equals(version, "3.6.4")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.6.4-3.6.5.sql");
            version = "3.6.5";
        }
        if(StringUtils.equals(version, "3.6.5")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.6.5-3.6.6.sql");
            version = "3.6.6";
        }
        if(StringUtils.equals(version, "3.6.6")){
            upgradeBySql(CebaPathUtil.getSqlFolder() + "/update/3.6.6-3.6.7.sql");
            version = "3.6.7";
        }
        CebaConfig.init();
    }

    private static void upgradeBySql(String filePath) {
        logger.info("开始升级sql：" + filePath);
        String sql = getText(filePath);
        List<String> sqlarr = getSql(sql);
        try{
            String tmp = "";
            for(int i=0; i<sqlarr.size(); i++){
                tmp = sqlarr.get(i);
                System.out.println(i+":"+tmp);
                tmp.replace("\r", "");
                tmp.replace("\n", "");
                if (tmp.isEmpty()) {
                    continue;
                }

                if(!SqlSessionManager.execute(sqlarr.get(i))) {
                    logger.error("更新config失败：" + sqlarr.get(i));
                }
            }

        }catch(Exception e){
            e.printStackTrace();
            logger.info("升级sql：" + filePath + "异常。" + e.getMessage());
        }
        logger.info("结束升级sql：" + filePath);
    }

    /*
     * getText方法吧path路径里面的文件按行读数来放入一个大的String里面去
     * 并在换行的时候加入\r\n
     */
    private static String getText(String path){
        File file = new File(path);
        if(!file.exists()||file.isDirectory()){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        try{
            FileInputStream fis = new FileInputStream(path);
            InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String temp = null;
            temp = br.readLine();
            while(temp!=null){
                if(temp.startsWith("#")||temp.startsWith("--")||temp.startsWith("/*")||temp.startsWith("//")){
                    temp = br.readLine();
                    continue;
                }
//                temp = temp.replaceAll("\r", "");
//                temp = temp.replaceAll("\n", "");
                sb.append("\r\n" + temp);
                temp = br.readLine();
            }
            br.close();

        }catch(Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }

    /*
     * getSqlArray方法
     * 从文件的sql字符串中分析出能够独立执行的sql语句并返回
     */
    private static List<String> getSql(String sql){
        String[] sqlarry = sql.split(";\r\n");  //用;把所有的语句都分开成一个个单独的句子
        return Arrays.asList(sqlarry);
    }
}
